package com.rew.canteenbox.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.rew.canteenbox.R;
import com.rew.canteenbox.bases.AppData;
import com.rew.canteenbox.models.Dishes;

/**
 *  计数器.
 *
 * Created by HuiWen Ren on 2016/11/27.
 */
public class FCounter extends Fragment
implements View.OnClickListener{

    private AppData appData;
    private View view;
    private Button addBtn;
    private Button minusBtn;
    private TextView numText;
    private Dishes dishes;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.item_counter, container,false);
        appData = (AppData) view.getContext().getApplicationContext();
        addBtn = (Button) view.findViewById(R.id.list_add_btn);
        minusBtn = (Button) view.findViewById(R.id.list_minus_btn);
        numText = (TextView) view.findViewById(R.id.tv_item_num);
        addBtn.setOnClickListener(this);
        minusBtn.setOnClickListener(this);
        fresh();
        return view;
    }

    public void setDish(Dishes dishes){
        this.dishes = dishes;
    }

    private void add() {
        appData.addOrder(dishes);
    }

    private void minus() {
        appData.minusOrder(dishes);
    }

    private void fresh(){
        int n = appData.getNum(dishes);
        if(n > 0 ){
            minusBtn.setVisibility(View.VISIBLE);
            numText.setVisibility(View.VISIBLE);
            numText.setText(Integer.toString(n));
        } else {
            minusBtn.setVisibility(View.GONE);
            numText.setVisibility(View.GONE);
        }
        view.refreshDrawableState();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.list_add_btn:
                add();
                break;
            case R.id.list_minus_btn:
                minus();
                break;
            default:break;
        }
        fresh();
    }
}
